package com.zto.security.web.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.sun.org.apache.xpath.internal.SourceTree;
import com.zto.security.dto.User;
import com.zto.security.dto.UserQueryCondition;
import com.zto.security.exception.UserNotExistException;
import com.zto.security.validate.Log;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;



/**
 * Created by xingyuchao on 2017/11/30.
 */
@RestController
@RequestMapping("/user")
public class UserController {

    //获取用户信息
    /*@GetMapping("/me")
    public Object getCurrentUser(){
        return SecurityContextHolder.getContext().getAuthentication();
    }*/

    //获取用户信息
    /*@GetMapping("/me")
    public Object getCurrentUser(Authentication authentication){
        return authentication;
    }
*/

    @GetMapping("/me")
    public Object getCurrentUser(@AuthenticationPrincipal UserDetails user){
        return user;
    }


    @GetMapping
    @JsonView(User.UserSimpleView.class)
    @ApiOperation(value = "用户查询服务", notes = "根据条件查找用户")
    public List<User> query(UserQueryCondition condition,
                            @PageableDefault(page = 2, size = 17, sort = "username",direction= Sort.Direction.DESC) Pageable pageable){

        System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE));   //打印toString

        System.out.println(pageable.getPageSize());
        System.out.println(pageable.getPageNumber());
        System.out.println(pageable.getSort());


        List<User> userList = new ArrayList<>();
        userList.add(new User());
        userList.add(new User());
        userList.add(new User());
        return userList;
    }


    //{id:\\d+}  表示只能是数字
    @GetMapping("/{id:\\d+}")
    @ApiOperation(value = "用户查询服务", notes = "根据条件ID查找用户")
    @JsonView(User.UserDetailView.class)
    public User queryById( @PathVariable String id) {

        //手动创建异常，用来测试
		throw new UserNotExistException("user not exist");
//        System.out.println("进入getInfo服务");
//        User user = new User();
//        user.setUsername("tom");
//        return user;
    }



    @ApiOperation(value = "新增用户服务", notes = "新增用户")
    @PostMapping
    public User addUser(@Valid @RequestBody User user, BindingResult errors) {

        if(errors.hasErrors()){
            errors.getAllErrors().stream().forEach( error -> System.out.println(error.getDefaultMessage()));
        }

        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getBirthday());

        user.setId("1");
        return user;
    }


    @ApiOperation(value = "更新用户服务", notes = "更新用户")
    @PutMapping("/{id:\\d+}")
    public User updateUser(@Valid @RequestBody User user, BindingResult errors) {

        if(errors.hasErrors()){
            //errors.getAllErrors().stream().forEach( error -> System.out.println(error.getDefaultMessage()));
            errors.getAllErrors().stream().forEach( error ->{
                FieldError fieldError = (FieldError)error;
                System.out.println(fieldError.getField()+":"+fieldError.getDefaultMessage());
            });
        }

        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getBirthday());

        user.setId("1");
        return user;
    }


    @Log(operationName="用户删除服务",operationType="01")
    @ApiOperation(value = "用户删除服务", notes = "删除用户")
    @DeleteMapping("/{id:\\d+}")
    public String deleteUser(@ApiParam("用户id") @PathVariable String id) {

        throw new UserNotExistException("user not exist");
        //System.out.println(id);
        //return "delete success";
    }
}
